package com.zoe.vhr.util;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.captcha.generator.MathGenerator;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.math.Calculator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Author Zoe.Zhang
 * @Date: 2021/07/28
 * @Description 生成验证码
 */
public class VerifyCodeUtil {

    private static final Logger logger = LoggerFactory.getLogger(VerifyCodeUtil.class);
    private String verifyCode;
    private String verifyCodeBase64;

    public VerifyCodeUtil() {
    }

    public VerifyCodeUtil(String verifyCode, String verifyCodeBase64) {
        this.verifyCode = verifyCode;
        this.verifyCodeBase64 = verifyCodeBase64;
    }

    public String getVerifyCode() {
        return verifyCode;
    }

    public void setVerifyCode(String verifyCode) {
        this.verifyCode = verifyCode;
    }

    public String getVerifyCodeBase64() {
        return verifyCodeBase64;
    }

    public void setVerifyCodeBase64(String verifyCodeBase64) {
        this.verifyCodeBase64 = verifyCodeBase64;
    }


    /**
     * 生成数学运算验证码
     *
     * @return
     */
    public static VerifyCodeUtil genVerifyCode() {
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(400, 100, 4, 4);
        circleCaptcha.setGenerator(new MathGenerator(1));
        String calc = circleCaptcha.getCode();
        Integer verifyCode = Convert.toInt(Calculator.conversion(calc));
        while (verifyCode < 0) {
            logger.info("验证码小于0====>{}", verifyCode);
            circleCaptcha.createCode();
            String code = circleCaptcha.getCode();
            verifyCode = Convert.toInt(Calculator.conversion(code));
            logger.info("重新生成验证码====>{}", verifyCode);
        }

        VerifyCodeUtil verifyCodeUtil = new VerifyCodeUtil(Convert.toStr(verifyCode), circleCaptcha.getImageBase64Data());
        return verifyCodeUtil;
    }
}
